for Loop

In Scala, for loop is also known as for-comprehensions. A for loop is a repetition control structure which allows us to write a loop that is executed a specific number of times. The loop enables us to perform n number of steps together in one line.

for( var x <- Range ){
   statement(s);
}

Here, x is a variable, <- operator is known as a generator, according to the name this operator is used to generate individual values from the range, and the range is the value which holds starting and ending values. The range can be represented by using either i to j or i until j.

For loop to print the value 0 to n.
object Main
{
def main(args: Array[String])
{
println("The value of x is:");
for( x <- 0 to 10)
{
println(s" The value is $x");
}
}
}
We can use until when we want to print value 0 to n-1.
object Demo {
def main(args: Array[String]) {
println("the value of x is");
for( x <- 1 until 10)
{
println(x)
}
}
}

Nested for Loop
Multiple ranges can be specified using semicolon (;) as the separator and the loop iterates for all possible combinations.
object demo {
def main(args: Array[String]) {
var id = 0;
var marks = 60;

for( id <- 1 to 2; marks <- 70 to 72){
println( "Student Id is : " + id );
println( "Marks is : " + marks );
}
}
}
output
Student Id is : 1
Marks is : 70
Student Id is : 1
Marks is : 71
Student Id is : 1
Marks is : 72
Student Id is : 2
Marks is : 70
Student Id is : 2
Marks is : 71
Student Id is : 2
Marks is : 72
object demo {
def main(args: Array[String]) {
val nums = Seq(1,2,3)
val letters = Seq('a', 'b', 'c')
val res = for {
n <- nums
c <- letters
} yield (n, c)
println(res)
}
}

for loop with collection
object demo {
def main(args: Array[String]) {
var marks = 0;
val Listmarks = List(60, 65, 70, 75, 80, 85);
for (m1 <- Listmarks) {
println("Marks :" + m1);
}
}
}
output
Marks :60
Marks :65
Marks :70
Marks :75
Marks :80
Marks :85


for loop with if conditions
object demo
{
def main(args: Array[String])
{
var rank = 0
val ranklist = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

// For loop with filters
for( rank <- ranklist if rank < 7; if rank > 2 )
{
println("Author rank is : " +rank);
}
}
}
output
Author rank is : 3
Author rank is : 4
Author rank is : 5
Author rank is : 6

for loop with yield
object demo {
def main(args:Array[String]) {
var id =0;
val Listid = List(4,5,6,7,8,10);
var result = for{ id <- Listid
if id <9; if id !=7
}yield id
for(id <- result) {
println("Student Id:"+id);
}
}
}
output
Student Id:4
Student Id:5
Student Id:6
Student Id:8

For Loop with yield Statements
object Demo {
def main(args: Array[String]) {
val name_seq= Seq("Scala", "is", "good")
val item_seq = Seq(1, 2, 3, 4, 5, 6, 7, 8)
val result = for {
a <- name_seq
b <- item_seq
} yield (a, b)
println(result)
}
}

object demo {
def main(args: Array[String]) {
val item_seq = Seq(1, 2, 3, 4, 5, 6, 7, 8)
for( item <- item_seq
if item < 5; if item > 3 )
{
println("Filtered number is : " +item);
}
}
}

No comments:

Post a Comment